﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel.DomainServices.Client;
using Arch.Samples.RiaServices.Commands;
using Arch.Samples.RiaServices.Infrastructure;
using Arch.Client.Commands;
using Arch.Samples.Model;
using Arch.Samples.RiaServices.Services;
using System.Linq;

namespace Arch.Samples.RiaServices.ViewModels
{
    public class SubCategoryListViewModel : CollectionViewModelBase<SubCategory>
    {
        public ICollection<GlobalCategory> Categories { get; set; }

        public SubCategoryListViewModel(TodoContext context)
            : base(context)
        {
            Categories = new ObservableCollection<GlobalCategory>();

            DeleteCommand = new DeleteCommand<SubCategoryListViewModel, SubCategory>(this, e => Context.Categories.Remove(e));
            DeleteSelectedCommand = new DeleteSelectedCommand<SubCategoryListViewModel, SubCategory>(this, e => Context.Categories.Remove(e));
            AddCommand = new RelayCommand(() =>
            {
                var c = new SubCategory();
                Context.EntityContainer.GetEntitySet<Category>().Add(c);
                Items.Add(c);
            });

            Refresh();
        }

        public void LoadCategories()
        {
            Context.Load(Context.GetGlobalCategoryQuery(), l => Categories.Reload(l.Entities));
        }

        public void LoadSubCategories()
        {
            Context.Load(Context.GetSubCategoryQuery(), l => Items.Reload(l.Entities));
        }

        public override void Refresh()
        {
            LoadCategories();
            LoadSubCategories();
        }
    }
}
